import { Injectable } from '@angular/core';
import { Headers, Http, RequestOptions } from '@angular/http';
import { Optional } from '@angular/core';

import 'rxjs/add/operator/toPromise';

import { Hero } from './hero.model';
import { HEROES } from './mock-heroes';

import { Logger } from '../../core/logger.service';

// 注入器 (injector) 是本机制的核心。
@Injectable()
export class HeroService {
  private heroesUrl = 'api/heroes';  // URL to web api
  private headers = new Headers({ 'Content-Type': 'application/json' });

  constructor(
    private http: Http,
    @Optional() private logger: Logger,
  )
  { }

  oldgetHeroes(): Promise<Hero[]> {
    return Promise.resolve(HEROES);
  };

  oldgetHero(id: number): Promise<Hero> {
    return this.getHeroes()
      .then(heroes => heroes.find(hero => hero.id === id));
  }

  /**
   * 删除英雄
   */
  delete(id: number): Promise<void> {
    const url = `${this.heroesUrl}/${id}`;
    return this.http.delete(url, { headers: this.headers })
      .toPromise()
      .then(() => null)
      .catch(this.handleError);
  }

  /**
   * 添加英雄
   */
  create(name: string): Promise<Hero> {
    return this.http
      .post(this.heroesUrl, JSON.stringify({ name: name }), { headers: this.headers })
      .toPromise()
      .then(res => res.json().data as Hero)
      .catch(this.handleError);
  }
  /**
   * 修改英雄
   */

  update(hero: Hero): Promise<Hero> {
    const url = `${this.heroesUrl}/${hero.id}`;
    return this.http
      .put(url, JSON.stringify(hero), { headers: this.headers })
      .toPromise()
      .then(() => hero)
      .catch(this.handleError);
  }
  /**
   *  获取英雄列表
   */
  getHeroes(): Promise<Hero[]> {

    this.logger.log(`Getting heroes for user.`);
    return this.http.get(this.heroesUrl)
      .toPromise()
      .then(response => response.json().data as Hero[])
      .catch(this.handleError);
  }
  /**
   *  错误处理
   */
  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error); // for demo purposes only
    return Promise.reject(error.message || error);
  }

  // private extractData(res: Response) {
  //   let body = res.json();
  //   return body.data || {};
  // }
  /**
   *  获取英雄详情
   */
  getHero(id: number): Promise<Hero> {
    const url = `${this.heroesUrl}/${id}`;
    return this.http.get(url)
      .toPromise()
      .then(response => response.json().data as Hero)
      .catch(this.handleError);
  }
  /**
   *  获取英雄列表 延迟2秒
   */
  getHeroesSlowly(): Promise<Hero[]> {
    return new Promise(resolve => {
      setTimeout(() => resolve(
        this.getHeroes()
      ), 2000)
    })
  };


}